<template>
  <ele-page class="p-0!" flex-table>
    <ele-bottom-bar v-if="current?.id" :teleported="true" :bodyStyle="{ overflow: 'inherit' }">
      <div v-if="treeData.filter(v => v.is_fh === 1).length">
        <el-button type="" @click="setChecked(1)">全选</el-button>
        <el-button type="" @click="setChecked(2)">反选</el-button>
        <el-button type="" @click="setChecked(3)">全不选</el-button>
        <el-divider direction="vertical" />
        <el-badge :show-zero="false" :value="selections.length">
          <el-button :disabled="!selections.length" type="primary" @click="deliveryBatch()">批量发货</el-button>
        </el-badge>
      </div>
      <template #extra>
        <el-button v-if="current.is_qx === 1" type="info" @click="cancel()">取消</el-button>
        <el-button v-if="current.is_fh === 1" type="primary" @click="delivery()">发货</el-button>
      </template>
    </ele-bottom-bar>
    <ele-split-panel
      flex-table
      size="300px"
      allow-collapse
      :custom-style="{ borderWidth: '0 1px 0 0', padding: '5px 0' }"
      :body-style="{ padding: '16px 16px 0 0', overflow: 'hidden' }"
      :style="{ height: '100%', overflow: 'visible' }"
    >
      <ele-loading
        :loading="loading"
        :style="{ flex: 1, paddingRight: '10px', overflow: 'auto' }"
      >
        <el-tree
          ref="treeRef"
          :data="treeData"
          highlight-current
          node-key="id"
          :props="{ label: 'pack_order_sn', disabled: (d) => d.is_fh !== 1 }"
          :show-checkbox="showCheckbox"
          :check-on-click-node="false"
          :check-on-click-leaf="false"
          :expand-on-click-node="false"
          :default-expand-all="true"
          :filter-node-method="filterNode"
          :style="{
            '--ele-tree-item-height': '40px',
            '--ele-tree-expand-padding': 0,
            '--ele-tree-expand-margin': 0,
          }"
          @node-click="onNodeClick"
          @check-change="onChange"
        >
          <template #default="{ data: d }">
            <div class="el-tree-node__label flex-ba w-full">
              <div style="margin-right: 4px">{{ d.pack_order_sn }}</div>
              <el-tag :type="getType(d.status)">
                {{ d.status_name }}
              </el-tag>
            </div>
          </template>
        </el-tree>
      </ele-loading>
      <template #body>
        <template v-if="current">
          <el-descriptions title="验收单详情" :column="4">
            <el-descriptions-item :width="100" label="打包单号">
              {{ current.pack_order_sn || '-' }}
            </el-descriptions-item>

            <el-descriptions-item :width="100" label="状态">
              <el-tag :type="getType(current.status, { YS: 'danger' })">{{ current.status_name }}</el-tag>
            </el-descriptions-item>

            <el-descriptions-item :width="100" label="创建人">
              {{ current.create_user_name || '-' }}
            </el-descriptions-item>

            <el-descriptions-item :width="100" label="创建时间">
              {{ current.create_time ? formatDate(current.create_time) : '-' }}
            </el-descriptions-item>
          </el-descriptions>
          <el-table
            :data="current.product_list"
            style="width: 100%"
            show-summary
            :summary-method="getSummaries"
            row-key="product_id"
            class="form-table"
          >
            <el-table-column type="index" label="序" width="60" align="center" />
            <el-table-column prop="product_name" label="商品名称" align="left" min-width="130" />
            <el-table-column prop="product_code" label="商品编码" align="center" />
            <el-table-column prop="unit" label="单位" align="center" />
            <el-table-column prop="num" label="打包数量" align="center" />
          </el-table>
        </template>
      </template>
    </ele-split-panel>
    <PageDelivery v-model="deliveryData.show" :data="deliveryData.list" @done="save" />
  </ele-page>
</template>

<script setup>
import PageDelivery from './delivery.vue'

const props = defineProps({
  orderId: Number,
  orderSn: String,
})

const emit = defineEmits(['done'])

const { formatDate, getType } = utils

const showEdit = ref(false)

const loading = ref(false)
const treeRef = ref(null)
const current = ref(null)
const treeData = ref([])

const selections = ref([])

const showCheckbox = ref(true)

const deliveryData = reactive({
  show: false,
  list: [],
})

function setChecked(value) {
  const keys = treeData.value.filter(v => v.is_fh === 1).map(v => v.id)
  if (value === 1) {
    treeRef.value.setCheckedKeys(keys)
  }
  else if (value === 2) {
    const checks = treeRef.value.getCheckedKeys()
    treeRef.value.setCheckedKeys([])
    treeRef.value.setCheckedKeys(keys.filter(v => !checks.includes(v)), true)
  }
  else if (value === 3) {
    treeRef.value.setCheckedKeys([])
  }
}

function delivery() {
  deliveryData.list = [current.value]
  deliveryData.show = true
}

function deliveryBatch() {
  deliveryData.list = treeData.value.filter(v => selections.value.includes(v.id))
  deliveryData.show = true
}

function save(data, cb) {
  const loadingBox = utils.message('请求中..', 'loading')
  const formData = {
    outbound_order_sn: props.orderSn,
    pack_list: deliveryData.list.map(v => ({ id: v.id })),
    logistics_id: 0,
    logistics_info: data,
  }
  utils.post('/outboundDelivery/record', formData).then((res) => {
    utils.message(res.msg, res.success)
    if (res.success) {
      query()
      deliveryData.show = false
    }
  }).finally(() => {
    cb && cb()
    loadingBox.close()
  })
}

function cancel() {
  utils.confirm(`是否确定取消打包单 ${current.value.pack_order_sn}`, '提示').then(() => {
    utils.post('/outboundPack/cancel', { pack_order_sn: current.value.pack_order_sn }).then((res) => {
      utils.message(res.msg, res.success)
      if (res.success) {
        query()
      }
    })
  })
}

/** 树过滤方法 */
function filterNode(value, data) {
  if (value)
    return !!(data.order_sn && data.order_sn.includes(value))

  return true
}

function onChange(data, bool) {
  if (bool) {
    if (!selections.value.includes(data.id))
      selections.value.push(data.id)
  }
  else {
    const index = selections.value.indexOf(data.id)
    if (index !== -1) {
      selections.value.splice(index, 1)
    }
  }
}

/** 选择数据 */
function onNodeClick(row) {
  if (row?.id) {
    current.value = row
    treeRef.value?.setCurrentKey?.(row.id)
  }
  else {
    current.value = null
  }
  showEdit.value = false
}

/** 查询 */
function query(isfirst) {
  loading.value = true
  utils.get('/outbound/packList', { outbound_id: props.orderId }).then((res) => {
    treeData.value = res.data
    if (res.data.length) {
      nextTick(() => {
        const row = res.data.find(v => v.id === current.value?.id) ?? res.data[0]
        onNodeClick(row)
      })
    }
  }).finally(() => {
    loading.value = false
  })
  if (!isfirst) {
    emit('done')
  }
}

query(true)

function getSummaries({ columns, data }) {
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    const keys = ['pick_num', 'inspect_num']
    if (keys.includes(column.property)) {
      sums[index] = data.reduce((acc, cur) => utils.Big(acc).plus(cur[column.property]).valueOf(), 0)
    }
    else {
      sums[index] = ''
    }
  })

  return sums
}
</script>

<style lang="scss" scoped>

</style>
